package com.quanyan.ic.datacenter.mq.service.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.ic.datacenter.constant.Constants;
import com.quanyan.ic.datacenter.constant.RedisConstant;
import com.quanyan.ic.datacenter.dao.*;
import com.quanyan.ic.datacenter.mapper.icData.entity.PlaceUnitLightAlarm;
import com.quanyan.ic.datacenter.model.AlarmDayReportParam;
import com.quanyan.ic.datacenter.model.LightOp;
import com.quanyan.ic.datacenter.model.PlaceUnitInfo;
import com.quanyan.ic.datacenter.mq.service.LightOpMsgConsumerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by jian.zhou on 2017/8/28.
 */
@Service
public class LightOpMsgConsumerServiceImpl implements LightOpMsgConsumerService {
    private static final Logger logger = LoggerFactory.getLogger(LightOpMsgConsumerService.class);

    @Autowired
    private PlaceUnitLightOpSourceDao placeUnitLightOpSourceDao;

    @Autowired
    PlaceOrderDao placeOrderDao;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    PlaceUnitLightAlarmDao placeUnitLightAlarmDao;

    @Autowired
    PlaceDao placeDao;
    @Autowired
    private AlarmDayReportOfCityDao alarmDayReportOfCityDao;
    @Autowired
    private AlarmDayReportOfPlaceDao alarmDayReportOfPlaceDao;
    @Autowired
    private AlarmTimePointReportOfCityDao alarmTimePointReportOfCityDao;
    @Autowired
    private AlarmTimePointReportOfPlaceDao alarmTimePointReportOfPlaceDao;


    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void consumerLightOpMsg(LightOp lightOp){
        logger.info(" light op consumer start{}" ,lightOp.toString());
        Integer id = placeUnitLightOpSourceDao.insert(lightOp);//入库
        lightOp.setId(id);
        Integer placeId = lightOp.getPlaceId();
        Integer placeUnitId = lightOp.getSiteId();
        Date dateTime = lightOp.getDt(); //开灯时间
        int orderCount = placeOrderDao.isOrderByDateTime(placeUnitId,dateTime);//当前时间订单数量
        if ( lightOp.getStatus() == 1){//开灯
            if ( orderCount < 1 ){ //无订单 开灯 异常
                String key = RedisConstant.getLightOpOnKey(placeId,placeUnitId);
                String jsonStr = redisTemplate.opsForValue().get(key);
                if ( jsonStr != null ){ // 开开
                    LightOp on  =  JSON.parseObject(jsonStr.toString(), LightOp.class);
                    Date startDateTime = on.getDt();
                    Date endDateTime = lightOp.getDt();
                    String ids = lightOp.getId() + "," + on.getId();
                    PlaceUnitLightAlarm insert = this.getInsert(placeUnitId);
                    insert.setOpIds(ids);
                    insert.setStartTime(startDateTime);
                    insert.setEndTime(endDateTime);
                    placeUnitLightAlarmDao.insert(insert);
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(lightOp));
                    if ( on.getType() == 1 &&lightOp.getType() == 1)//手动
                      this.insertReport(insert,1);
                    else
                      this.insertReport(insert,null);

                }else{
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(lightOp));
                }
            }
        } else {
            String key = RedisConstant.getLightOpOnKey(placeId,placeUnitId);
            String jsonStr = redisTemplate.opsForValue().get(key);
            if ( jsonStr != null ){ // 是否有对应关灯的数据
                LightOp on  =  JSON.parseObject(jsonStr.toString(), LightOp.class);

                Date startDateTime = on.getDt();
                Date endDateTime = lightOp.getDt();
                String ids = lightOp.getId() + "," + on.getId();
                PlaceUnitLightAlarm insert = this.getInsert(placeUnitId);
                insert.setOpIds(ids);
                insert.setStartTime(startDateTime);
                insert.setEndTime(endDateTime);
                placeUnitLightAlarmDao.insert(insert);
                redisTemplate.delete(key);
                if ( on.getType() == 1 && lightOp.getType() == 1)//手动
                    this.insertReport(insert,1);
                else
                    this.insertReport(insert,null);
            }else {
                logger.info("light op no close msg  =================>");
            }
        }

        logger.info(" light op consumer end {}");

    }

    public PlaceUnitLightAlarm getInsert(Integer siteId){
        PlaceUnitInfo placeUnitInfo = placeDao.getPlaceUnitInfo(siteId);

        PlaceUnitLightAlarm insert = new PlaceUnitLightAlarm();
        insert.setPlaceId(placeUnitInfo.getPlaceId());
        insert.setPlaceName(placeUnitInfo.getPlaceName());
        insert.setCityId(placeUnitInfo.getCityId());
        insert.setCityName(placeUnitInfo.getCityName());
        insert.setCategoryId(placeUnitInfo.getCategoryId());
        insert.setCategoryName(placeUnitInfo.getCategoryName());
        insert.setPlaceUnitName(placeUnitInfo.getPlaceUnitName());
        insert.setPlaceUnitId(placeUnitInfo.getPlaceUnitId());
        return insert;
    }


    public void insertReport(PlaceUnitLightAlarm insert ,Integer type){
        long between=( insert.getEndTime().getTime() - insert.getStartTime().getTime())/1000;//除以1000是为了转换成秒
        Long min =between/60;;

        AlarmDayReportParam alarmDayReportParam = new AlarmDayReportParam();
        alarmDayReportParam.setHandLight(type);
        alarmDayReportParam.setCityId(insert.getCityId());
        alarmDayReportParam.setDate(insert.getStartTime());
        alarmDayReportParam.setType(Constants.AlarmsType.alarms_type_light);
        alarmDayReportParam.setMin(min.intValue());
        alarmDayReportParam.setPlaceId(insert.getPlaceId());
        alarmDayReportParam.setPlaceName(insert.getPlaceName());
        alarmDayReportParam.setStartTimeInt(insert.getStartTime().getHours());
        alarmDayReportOfCityDao.consumerOrder(alarmDayReportParam);
        alarmDayReportOfPlaceDao.consumerOrder(alarmDayReportParam);
        alarmTimePointReportOfCityDao.insertAlarmTimePointCity(alarmDayReportParam);
        alarmTimePointReportOfPlaceDao.insertAlarmTimePointPlace(alarmDayReportParam);



    }
}
